package com.example.servicedemo1;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private  static final String TAG="tag";
    private ServiceConnection mcn=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            try {
                String result=IMyAidlInterface.Stub.asInterface(service).getRemoteData("应用内跨进程数据");
                Log.d(TAG,result);
            } catch (RemoteException e) {
                e.printStackTrace();
            }

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startService(new Intent(MainActivity.this,MyService.class));
        initView();
    }
    private void initView(){
        Button button=findViewById(R.id.fo_butn);
        Button button1=findViewById(R.id.butn_bind);
        Button button2=findViewById(R.id.butn_unbind);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent("com.example.aidl.REMOTE_SERVICE");
                intent.setPackage("com.example.servicedemo1");
                bindService(intent,mcn,BIND_AUTO_CREATE);

            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            unbindService(mcn);

            }
        });
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startForegroundService(new Intent(MainActivity.this,MyService.class));
            }
        });
    }
}